package whisper.api.gateway.frame.auth.filter.permission;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by JT on 2017/9/25.
 */
@Service(value = "PermissionAccessDecisionManager")
public class PermissionAccessDecisionManager implements AccessDecisionManager {


    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        /**
         * 该URL没有赋予任何角色，则任何用户都可以访问
         */
        if (null == configAttributes && configAttributes.size() <= 0) return;

        /**
         * 用户持有的角色 与 该权限所需要的角色 对比：
         *      如果用户拥有该角色，则允许访问
         *      如果用户没有该角色，则不允许访问
         */
        Set<String> needRoles = new HashSet<>();
        for (ConfigAttribute attribute : configAttributes) {
            needRoles.add(attribute.getAttribute());
        }

        Set<String> haveRoles = new HashSet<>();
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            haveRoles.add(authority.getAuthority());
        }

        haveRoles.retainAll(needRoles);
        if (haveRoles.size() > 0) return;

        throw new AccessDeniedException("权限不足！");

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
